package com.itdachang.design.creatation.prototype;

import java.util.HashMap;
import java.util.Map;

/**
 * @author gcq
 * @Create 2022-02-06
 */
public class GuiguMybatis {

    /**
     * 用户缓存
     */
    private Map<String, User> userCache = new HashMap<>();

    /**
     * 从数据库中查询数据
     * @param username
     * @return
     */
    public User getUser(String username) throws Exception {
        User user = null;
        // 缓存中没有
        if(!userCache.containsKey(username)) {
            user = this.getUserFormDb(username);
            user = (User) user.clone();
        } else {
            // 从缓存中直接拿 脏缓存问题
            // 原型已经拿到，但是不能直接给
            user = userCache.get(username);
            user = (User) user.clone();
        }
        return user;
    }

    /**
     * 从数据库中查询数据
     * @param username
     * @return
     */
    public User getUserFormDb(String username) throws Exception{
        System.out.println("从数据库中查到：" + username);
        User user = new User();
        user.setUsername(username);
        user.setAge(18);
        // 查询后，放到缓存中 给缓存中放一个 clone
        userCache.put(username, (User) user.clone());
        return user;
    }
}